package com.drinks.yiniang.ui.activity.user.address;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.user.address.AddressInfoJson;
import com.drinks.yiniang.entity.user.address.DeliverAddressJson;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.utils.GetJsonDataUtil;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.pickerview.OptionsPickerView;
import com.hansen.library.pickerview.bean.city.CityBean;
import com.hansen.library.pickerview.bean.city.CityJson;
import com.hansen.library.ui.widget.layout.TextEditLayout;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.widget.layout.TextTextArrowLayout;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 添加收货地址页面
 *
 * @author han
 * @date 2019/09/06
 */
public class AddAddressActivity extends BaseTranBarActivity implements OnNavgationBarClickListener {

    //nav
    private NavigationBarLayout nav_bar_add_address;
    //收货人
    private TextEditLayout tel_add_address_receiver;
    //手机号
    private TextEditLayout tel_add_address_phone;
    //地区
    private TextTextArrowLayout tta_add_address_area;
    //地址详情
    private TextEditLayout tel_add_address_details;
    //设置为默认地址
    private TextView tv_add_address_default;
    //保存
    private Button btn_add_address_save;

    //省市区
    private OptionsPickerView pvAddressOptions;

    private ArrayList<CityJson> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<CityBean>>> options3Items = new ArrayList<>();

    //地址id, (编辑地址时存在)
    private String mAddressId;
    private String mProvinceId;
    private String mCityId;
    private String mDistrictId;

    //是否默认地址
    private boolean isDefault;

    @Override
    protected void initView() {
        nav_bar_add_address = findViewById(R.id.nav_bar_add_address);

        tel_add_address_receiver = findViewById(R.id.tel_add_address_receiver);
        tel_add_address_phone = findViewById(R.id.tel_add_address_phone);
        tta_add_address_area = findViewById(R.id.tta_add_address_area);
        tel_add_address_details = findViewById(R.id.tel_add_address_details);

        tv_add_address_default = findViewById(R.id.tv_add_address_default);

        btn_add_address_save = findViewById(R.id.btn_add_address_save);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        if (getIntent() != null) {
            mAddressId = getIntent().getStringExtra(Constants.KeyAddressId);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 写子线程中的操作,解析省市区数据
                initJsonData();
            }
        }).start();

        getAddressInfo();
    }

    @Override
    protected void initListener() {
        nav_bar_add_address.setOnNavgationBarClickListener(this);
        tta_add_address_area.setOnClickListener(this);
        tv_add_address_default.setOnClickListener(this);
        btn_add_address_save.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tta_add_address_area://省市区
                showPickerView();
                break;
            case R.id.tv_add_address_default://设置为默认地址
                switchDefaultStatus();
                break;
            case R.id.btn_add_address_save://保存地址
                saveAddress();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_add_address;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    //保存地址
    private void saveAddress() {
        if (StringUtils.isEmpty(tel_add_address_receiver.getEditText())) {
            ToastUtils.showShort(getString(R.string.text_hint_input_receiver));
            return;
        }

        if (StringUtils.isEmpty(tel_add_address_phone.getEditText())) {
            ToastUtils.showShort(getString(R.string.text_hint_input_contact_way));
            return;
        }

        if (!StringUtils.isPhone(tel_add_address_phone.getEditText())) {
            ToastUtils.showShort(getString(R.string.text_hint_input_true_phone_num));
            return;
        }

        if (StringUtils.isEmpty(mProvinceId) || StringUtils.isEmpty(mCityId) || StringUtils.isEmpty(mDistrictId)) {
            ToastUtils.showShort(getString(R.string.text_select_province_city_area));
            return;
        }

        if (StringUtils.isEmpty(tel_add_address_details.getEditText())) {
            ToastUtils.showShort(getString(R.string.text_hint_input_street_floor_num));
            return;
        }

        showLoadingDialog();

        if(!StringUtils.isEmpty(mAddressId)) {//地址id存在，进入修改地址
            modifyAddress();
            return;
        }

        String name = tel_add_address_receiver.getEditText();
        String mobile = tel_add_address_phone.getEditText();
        String address = tel_add_address_details.getEditText();
        String isDefaultStatus = isDefault ? "1" : "0";

        UserApiIO.getInstance().addDeliverAddress(name, mobile, mProvinceId, mCityId, mDistrictId, address, isDefaultStatus,
                new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(BaseJson res) {
                        setResult(Constants.RESULT_CODE_NORMAL);
                        finish();
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //修改地址
    private void modifyAddress() {
        String name = tel_add_address_receiver.getEditText();
        String mobile = tel_add_address_phone.getEditText();
        String address = tel_add_address_details.getEditText();
        String isDefaultStatus = isDefault ? "1" : "0";

        UserApiIO.getInstance().modifyDeliverAddress(mAddressId, name, mobile, mProvinceId, mCityId, mDistrictId, address, isDefaultStatus,
                new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(BaseJson res) {
                        setResult(Constants.RESULT_CODE_NORMAL);
                        finish();
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //根据地址id获取地址信息
    private void getAddressInfo() {
        if (StringUtils.isEmpty(mAddressId)) {
            return;
        }

        showLoadingDialog();

        UserApiIO.getInstance().getDeliverAddressInfo(mAddressId, new APIRequestCallback<AddressInfoJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AddressInfoJson res) {
                setAddressData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setAddressData(DeliverAddressJson.DeliverAddressData data) {
        tel_add_address_receiver.setEditText(data.getReal_name());
        tel_add_address_phone.setEditText(data.getMobile());
        tel_add_address_details.setEditText(data.getAddress());

        if (data.getRegion_province() != null && data.getRegion_city() != null && data.getRegion_district() != null) {
            mProvinceId = data.getRegion_province().getRegion_id();
            mCityId = data.getRegion_city().getRegion_id();
            mDistrictId = data.getRegion_district().getRegion_id();

            if (!StringUtils.isEmpty(mProvinceId) && !StringUtils.isEmpty(mCityId) && !StringUtils.isEmpty(mDistrictId)) {
                StringBuilder builder = new StringBuilder();
                builder.append(StringUtils.getNoNullString(data.getRegion_province().getRegion_name()));
                builder.append(" ");
                builder.append(StringUtils.getNoNullString(data.getRegion_city().getRegion_name()));
                builder.append(" ");
                builder.append(StringUtils.getNoNullString(data.getRegion_district().getRegion_name()));
                tta_add_address_area.setArrowText(builder.toString());
            }
        }

        isDefault = Constants.STATUS_GLOBAL_YES.equals(data.getIs_default());

        if (isDefault) {//是默认地址
            tv_add_address_default.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_checkbox_selected, 0, 0, 0);
        } else {
            tv_add_address_default.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_checkbox_normal, 0, 0, 0);
        }
    }

    //切换默认状态
    private void switchDefaultStatus() {
        if (isDefault) {
            isDefault = false;
            tv_add_address_default.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_checkbox_normal, 0, 0, 0);
        } else {
            isDefault = true;
            tv_add_address_default.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_checkbox_selected, 0, 0, 0);
        }
    }

    //省市区
    private void showPickerView() {// 弹出选择器
        if (options1Items == null || options1Items.size() <= 0) {
            return;
        }

        if (pvAddressOptions == null) {
            pvAddressOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    mProvinceId = options1Items.get(options1).getPickerViewId();
                    mCityId = options2Items.get(options1).get(options2).getRegion_id();
                    mDistrictId = options3Items.get(options1).get(options2).get(options3).getRegion_id();

                    tta_add_address_area.setArrowText(options1Items.get(options1).getPickerViewText() + " " + options2Items.get(options1).get(options2).getRegion_name() + " "
                            + options3Items.get(options1).get(options2).get(options3).getRegion_name());
                }
            }).setTitleText(getString(R.string.text_in_area))
                    .build();
            pvAddressOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        }

        pvAddressOptions.show();
    }

    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = GetJsonDataUtil.getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<CityJson> jsonBean = GetJsonDataUtil.parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items.addAll(jsonBean);

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<CityBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getItems().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getItems().get(c));//添加城市

                ArrayList<CityBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getItems().get(c).getItems() == null
                        || jsonBean.get(i).getItems().get(c).getItems().size() == 0) {
                    City_AreaList.add(new CityBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).getItems().get(c).getItems().size(); d++) {//该城市对应地区所有数据
                        City_AreaList.add(jsonBean.get(i).getItems().get(c).getItems().get(d));//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }
}
